home *** CD-ROM | disk | FTP | other *** search
/ C/C++ 3D Game Tools / C-C++ 3D Game Tools.iso / tools / asm.txt < prev    next >
Text File  |  1997-02-25  |  72KB  |  1,683 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.                     IBM Personal Computer Assembly
  8.                          Language Tutorial
  9.  
  10.  
  11.  
  12.                           Joshua Auerbach
  13.                           Yale University
  14.                         Yale Computer Center
  15.                          175 Whitney Avenue
  16.                            P. O. Box 2112
  17.                      New Haven, Connecticut 06520
  18.  
  19.                          Installation Code YU
  20.  
  21.                  Integrated Personal Computers Project
  22.                         Communications Group
  23.                  Communications and Data Base Division
  24.  
  25.                             Session C316
  26.  
  27.  
  28.  
  29.  
  30. This talk is for people who are just getting started with the PC MACRO
  31. Assembler.  Maybe you are just contemplating doing some coding in
  32. assembler, maybe you have tried it with mixed success.  If you are here to
  33. get aimed in the right direction, to get off to a good start with the
  34. assembler, then you have come for the right reason.  I can't promise you'll
  35. get what you want, but I'll do my best.
  36.  
  37. On the other hand, if you have already turned out some working assembler
  38. code, then this talk is likely to be on the elementary side for you.  If
  39. you want to review a few basics and have no where else pressing to go, then
  40. by all means stay.
  41.  
  42.  
  43.  
  44. Why Learn Assembler?
  45. ____________________
  46. Why Learn Assembler?
  47. Why Learn Assembler?
  48. Why Learn Assembler?
  49.  
  50.  
  51. The reasons for LEARNING assembler are not the same as the reasons for
  52. USING it in a particular application.  But, we have to start with some of
  53. the reasons for using it and then I think the reasons for learning it will
  54. become clear.
  55.  
  56. First, let's dispose of a bad reason for using it.  Don't use it just
  57. because you think it is going to execute faster.  A particular sequence of
  58. ordinary bread-and-butter computations written in PASCAL, C, FORTRAN, or
  59. compiled BASIC can do the job just about as fast as the same algorithm
  60. coded in assembler.  Of course, interpretive BASIC is slower, but if you
  61. have a BASIC application which runs too slow you probably want to try com-
  62.  
  63.  
  64. IBM PC Assembly Language Tutorial                                         1
  65.  
  66.  
  67.  
  68. piling it before you think too much about translating parts of it to
  69. another language.
  70.  
  71. On the other hand, high level languages do tend to isolate you from the
  72. machine.  That is both their strength and their weakness.  Usually, when
  73. implemented on a micro, a high level language provides an escape mechanism
  74. to the underlying operating system or to the bare machine.  So, for
  75. example, BASIC has its PEEK and POKE.  But, the route to the bare machine
  76. is often a circuitous one, leading to tricky programming which is hard to
  77. follow.
  78.  
  79. For those of us working on PC's connected to SHARE-class mainframes, we are
  80. generally concerned with three interfaces:  the keyboard, the screen, and
  81. the communication line or lines.  All three of these entities raise machine
  82. dependent issues which are imperfectly addressed by the underlying operat-
  83. ing system or by high level languages.
  84.  
  85. Sometimes, the system or the language does too little for you.  For
  86. example, with the asynch adapter, the system provides no interrupt handler,
  87. no buffer, and no flow control.  The application is stuck with the respon-
  88. sibility for monitoring that port and not missing any characters, then
  89. deciding what to do with all errors.  BASIC does a reasonable job on some
  90. of this, but that is only BASIC.  Most other languages do less.
  91.  
  92. Sometimes, the system may do too much for you.  System support for the key-
  93. board is an example.  At the hardware level, all 83 keys on the keyboard
  94. send unique codes when they are pressed, held down, and released.  But,
  95. someone has decided that certain keys, like Num Lock and Scroll Lock are
  96. going to do certain things before the application even sees them and can't
  97. therefore be used as ordinary keys.
  98.  
  99. Sometimes, the system does about the right amount of stuff but does it less
  100. efficiently then it should.  System support for the screen is in this
  101. class.  If you use only the official interface to the screen you sometimes
  102. slow your application down unacceptably.  I said before, don't use assem-
  103. bler just to speed things up, but there I was talking about mainline code,
  104. which generally can't be speeded up much by assembler coding.  A critical
  105. system interface is a different matter:  sometimes we may have to use
  106. assembler to bypass a hopelessly inefficient implementation.  We don't want
  107. to do this if we can avoid it, but sometimes we can't.
  108.  
  109. Assembly language code can overcome these deficiencies.  In some cases, you
  110. can also overcome these deficiencies by judicious use of the escape valves
  111. which your high level language provides.  In BASIC, you can PEEK and POKE
  112. and INP and OUT your way around a great many issues.  In many other lan-
  113. guages you can issue system calls and interrupts and usually manage, one
  114. way or other, to modify system memory.  Writing handlers to take real-time
  115. hardware interrupts from the keyboard or asynch port, though, is still
  116. going to be a problem in most languages.  Some languages claim to let you
  117. do it but I have yet to see an acceptably clean implementation done that
  118. way.
  119.  
  120. The real reason while assembler is better than "tricky POKEs" for writing
  121. machine-dependent code, though, is the same reason why PASCAL is better
  122. than assembler for writing a payroll package:  it is easier to maintain.
  123.  
  124.  
  125. IBM PC Assembly Language Tutorial                                         2
  126.  
  127.  
  128.  
  129. Let the high level language do what it does best, but recognize that there
  130. are some things which are best done in assembler code.  The assembler,
  131. unlike the tricky POKE, can make judicious use of equates, macros, labels,
  132. and appropriately placed comments to show what is really going on in this
  133. machine-dependent realm where it thrives.
  134.  
  135. So, there are times when it becomes appropriate to write in assembler; giv-
  136. en that, if you are a responsible programmer or manager, you will want to
  137. be "assembler-literate" so you can decide when assembler code should be
  138. written.
  139.  
  140. What do I mean by "assembler-literate?"  I don't just mean understanding
  141. the 8086 architecture; I think, even if you don't write much assembler code
  142. yourself, you ought to understand the actual process of turning out assem-
  143. bler code and the various ways to incorporate it into an application.  You
  144. ought to be able to tell good assembler code from bad, and appropriate
  145. assembler code from inappropriate.
  146.  
  147.  
  148.  
  149. Steps to becoming ASSEMBLER-LITERATE
  150. ____________________________________
  151. Steps to becoming ASSEMBLER-LITERATE
  152. Steps to becoming ASSEMBLER-LITERATE
  153. Steps to becoming ASSEMBLER-LITERATE
  154.  
  155.  
  156. 1.  Learn the 8086 architecture and most of the instruction set.  Learn
  157.     what you need to know and ignore what you don't.  Reading:  The 8086
  158.     Primer by Stephen Morse, published by Hayden.  You need to read only
  159.     two chapters, the one on machine organization and the one on the
  160.     instruction set.
  161.  
  162. 2.  Learn about a few simple DOS function calls.  Know what services the
  163.     operating system provides.  If appropriate, learn a little about other
  164.     systems too.  It will aid portability later on.  Reading:  appendices D
  165.     and E of the PC DOS manual.
  166.  
  167. 3.  Learn enough about the MACRO assembler and the LINKer to write some
  168.     simple things that really work.  Here, too, the main thing is figuring
  169.     out what you don't need to know.  Whatever you do, don't study the sam-
  170.     ple programs distributed with the assembler unless you have nothing
  171.     better!
  172.  
  173. 4.  At the same time as you are learning the assembler itself, you will
  174.     need to learn a few tools and concepts to properly combine your assem-
  175.     bler code with the other things you do.  If you plan to call assembler
  176.     subroutines from a high level language, you will need to study the
  177.     interface notes provided in your language manual.  Usually, this forms
  178.     an appendix of some sort.  If you plan to package your assembler rou-
  179.     tines as .COM programs you will need to learn to do this.  You should
  180.     also learn to use DEBUG.
  181.  
  182. 5.  Read the Technical Reference, but very selectively.  The most important
  183.     things to know are the header comments in the BIOS listing.  Next, you
  184.     will want to learn about the RS 232 port and maybe about the video
  185.     adapters.
  186.  
  187.  
  188.  
  189.  
  190. IBM PC Assembly Language Tutorial                                         3
  191.  
  192.  
  193.  
  194. Notice that the key thing in all five phases is being selective.  It is
  195. easy to conclude that there is too much to learn unless you can throw away
  196. what you don't need.  Most of the rest of this talk is going to deal with
  197. this very important question of what you need and don't need to learn in
  198. each phase.  In some cases, I will have to leave you to do almost all of
  199. the learning, in others, I will teach a few salient points, enough, I hope,
  200. to get you started.  I hope you understand that all I can do in an hour is
  201. get you started on the way.
  202.  
  203.  
  204.  
  205. Phase 1:  Learn the architecture and instruction set
  206. ____________________________________________________
  207. Phase 1:  Learn the architecture and instruction set
  208. Phase 1:  Learn the architecture and instruction set
  209. Phase 1:  Learn the architecture and instruction set
  210.  
  211.  
  212. The Morse book might seem like a lot of book to buy for just two really
  213. important chapters; other books devote a lot more space to the instruction
  214. set and give you a big beautiful reference page on each instruction.  And,
  215. some of the other things in the Morse book, although interesting, really
  216. aren't very vital and are covered too sketchily to be of any real help.
  217. The reason I like the Morse book is that you can just read it; it has a
  218. very conversational style, it is very lucid, it tells you what you really
  219. need to know, and a little bit more which is by way of background; because
  220. nothing really gets belabored to much, you can gracefully forget the things
  221. you don't use.  And, I very much recommend READING Morse rather than study-
  222. ing it.  Get the big picture at this point.
  223.  
  224. Now, you want to concentrate on those things which are worth fixing in mem-
  225. ory.  After you read Morse, you should relate what you have learned to this
  226. outline.
  227.  
  228. 1.  You want to fix in your mind the idea of the four segment registers
  229.     CODE, DATA, STACK, and EXTRA.  This part is pretty easy to grasp.  The
  230.     8086 and the 8088 use 20 bit addresses for memory, meaning that they
  231.     can address up to 1 megabyte of memory.  But, the registers and the
  232.     address fields in all the instructions are no more that 16 bits long.
  233.     So, how to address all of that memory?  Their solution is to put
  234.     together two 16 bit quantities like this:
  235.  
  236.       calculation  SSSS0   ---- value in the relevant segment register SHL 4
  237.       depicted in   AAAA   ---- apparent address from register or instruction
  238.       hexadecimal --------
  239.                    RRRRR   ---- real address placed on address bus
  240.  
  241.     In other words, any time memory is accessed, your program will supply a
  242.     sixteen bit address.  Another sixteen bit address is acquired from a
  243.     segment register, left shifted four bits (one nibble) and added to it
  244.     to form the real address.  You can control the values in the segment
  245.     registers and thus access any part of memory you want.  But the segment
  246.     registers are specialized:  one for code, one for most data accesses,
  247.     one for the stack (which we'll mention again) and one "extra" one for
  248.     additional data accesses.
  249.  
  250.     Most people, when they first learn about this addressing scheme become
  251.     obsessed with converting everything to real 20 bit addresses.  After a
  252.     while, though, you get use to thinking in segment/offset form.  You
  253.  
  254.  
  255. IBM PC Assembly Language Tutorial                                         4
  256.  
  257.  
  258.  
  259.     tend to get your segment registers set up at the beginning of the pro-
  260.     gram, change them as little as possible, and think just in terms of
  261.     symbolic locations in your program, as with any assembly language.
  262.  
  263.       EXAMPLE:
  264.            MOV  AX,DATASEG
  265.            MOV  DS,AX          ;Set value of Data segment
  266.            ASSUME DS:DATASEG   ;Tell assembler DS is usable
  267.            .......
  268.            MOV  AX,PLACE       ;Access storage symbolically by 16 bit address
  269.  
  270.     In the above example, the assembler knows that no special issues are
  271.     involved because the machine generally uses the DS register to complete
  272.     a normal data reference.
  273.  
  274.     If you had used ES instead of DS in the above example, the assembler
  275.     would have known what to do, also.  In front of the MOV instruction
  276.     which accessed the location PLACE, it would have placed the ES segment
  277.     prefix.  This would tell the machine that ES should be used, instead of
  278.     DS, to complete the address.
  279.  
  280.     Some conventions make it especially easy to forget about segment regis-
  281.     ters.  For example, any program of the COM type gets control with all
  282.     four segment registers containing the same value.  This program exe-
  283.     cutes in a simplified 64K address space.  You can go outside this
  284.     address space if you want but you don't have to.
  285.  
  286. 2.  You will want to learn what other registers are available and learn
  287.     their personalities:
  288.  
  289.        AX and DX are general purpose registers.  They become special only
  290.         when accessing machine and system interfaces.
  291.  
  292.        CX is a general purpose register which is slightly specialized for
  293.         counting.
  294.  
  295.        BX is a general purpose register which is slightly specialized for
  296.         forming base-displacement addresses.
  297.  
  298.        AX-DX can be divided in half, forming AH, AL, BH, BL, CH, CL, DH,
  299.         DL.
  300.  
  301.        SI and DI are strictly 16 bit.  They can be used to form indexed
  302.         addresses (like BX) and they are also used to point to strings.
  303.  
  304.        SP is hardly ever manipulated.  It is there to provide a stack.
  305.  
  306.        BP is a manipulable cousin to SP.  Use it to access data which has
  307.         been pushed onto the stack.
  308.  
  309.        Most sixteen bit operations are legal (even if unusual) when per-
  310.         formed in SI, DI, SP, or BP.
  311.  
  312.  
  313.  
  314.  
  315.  
  316. IBM PC Assembly Language Tutorial                                         5
  317.  
  318.  
  319.  
  320. 3.  You will want to learn the classifications of operations available
  321.     WITHOUT getting hung up in the details of how 8086 opcodes are con-
  322.     structed.
  323.  
  324.     8086 opcodes are complex.  Fortunately, the assembler opcodes used to
  325.     assemble them are simple.  When you read a book like Morse, you will
  326.     learn some things which are worth knowing but NOT worth dwelling on.
  327.  
  328.     a.  8086 and 8088 instructions can be broken up into subfields and bits
  329.         with names like R/M, MOD, S and W. These parts of the instruction
  330.         modify the basic operation in such ways as whether it is 8 bit or
  331.         16 bit, if 16 bit, whether all 16 bits of the data are given,
  332.         whether the instruction is register to register, register to
  333.         memory, or memory to register, for operands which are registers,
  334.         which register, for operands which are memory, what base and index
  335.         registers should be used in finding the data.
  336.  
  337.     b.  Also, some instructions are actually represented by several differ-
  338.         ent machine opcodes depending on whether they deal with immediate
  339.         data or not, or on other issues, and there are some expedited forms
  340.         which assume that one of the arguments is the most commonly used
  341.         operand, like AX in the case of arithmetic.
  342.  
  343.     There is no point in memorizing any of this detail; just distill the
  344.     bottom line, which is, what kinds of operand combinations EXIST in the
  345.     instruction set and what kinds don't.  If you ask the assembler to ADD
  346.     two things and the two things are things for which there is a legal ADD
  347.     instruction somewhere in the instruction set, the assembler will find
  348.     the right instruction and fill in all the modifier fields for you.
  349.  
  350.     I guess if you memorized all the opcode construction rules you might
  351.     have a crack at being able to disassemble hex dumps by eye, like you
  352.     may have learned to do somewhat with 370 assembler.  I submit to you
  353.     that this feat, if ever mastered by anyone, would be in the same class
  354.     as playing the "Minute Waltz" in a minute; a curiosity only.
  355.  
  356.     Here is the basic matrix you should remember:
  357.  
  358.  
  359.  
  360.  
  361.  
  362.  
  363.  
  364.  
  365.  
  366.  
  367.  
  368.  
  369.  
  370.  
  371.  
  372.  
  373.  
  374.  
  375.  
  376.  
  377. IBM PC Assembly Language Tutorial                                         6
  378.  
  379.  
  380.  
  381.          Two operands:          One operand:
  382.           R <-- M                R
  383.           M <-- R                M
  384.           R <-- R                S *
  385.           R|M <-- I
  386.           R|M <-- S  *
  387.           S <-- R|M  *
  388.  
  389.       * -- data moving instructions (MOV, PUSH, POP) only
  390.       S -- segment register (CS, DS, ES, SS)
  391.       R -- ordinary register (AX, BX, CX, DX, SI, DI, BP, SP,
  392.                               AH, AL, BH, BL, CH, CL, DH, DL)
  393.       M -- one of the following
  394.                pure address
  395.                [BX]+offset
  396.                [BP]+offset
  397.                any of the above indexed by SI
  398.                any of the first three indexed by DI
  399.  
  400. 4.  Of course, you want to learn the operations themselves.  As I've sug-
  401.     gested, you want to learn the op codes as the assembler presents them,
  402.     not as the CPU machine language presents them.  So, even though there
  403.     are many MOV op codes you don't need to learn them.  Basically, here is
  404.     the instruction set:
  405.  
  406.     a.  Ordinary two operand instructions.  These instructions perform an
  407.         operation and leave the result in place of one of the operands.
  408.         They are
  409.  
  410.         1)  ADD and ADC -- addition, with or without including a carry from
  411.             a previous addition
  412.  
  413.         2)  SUB and SBB -- subtraction, with or without including a borrow
  414.             from a previous subtraction
  415.  
  416.         3)  CMP -- compare.  It is useful to think of this as a subtraction
  417.             with the answer being thrown away and neither operand actually
  418.             changed
  419.  
  420.         4)  AND, OR, XOR -- typical boolean operations
  421.  
  422.         5)  TEST -- like an AND, except the answer is thrown away and nei-
  423.             ther operand is changed.
  424.  
  425.         6)  MOV -- move data from source to target
  426.  
  427.         7)  LDS, LES, LEA -- some specialized forms of MOV with side
  428.             effects
  429.  
  430.     b.  Ordinary one operand instructions.  These can take any of the oper-
  431.         and forms described above.  Usually, the perform the operation and
  432.         leave the result in the stated place:
  433.  
  434.         1)  INC -- increment contents
  435.  
  436.  
  437.  
  438. IBM PC Assembly Language Tutorial                                         7
  439.  
  440.  
  441.  
  442.         2)  DEC -- decrement contents
  443.  
  444.         3)  NEG -- twos complement
  445.  
  446.         4)  NOT -- ones complement
  447.  
  448.         5)  PUSH -- value goes on stack (operand location itself unchanged)
  449.  
  450.         6)  POP -- value taken from stack, replaces current value
  451.  
  452.     c.  Now you touch on some instructions which do not follow the general
  453.         operand rules but which require the use of certain registers.  The
  454.         important ones are
  455.  
  456.         1)  The multiply and divide instructions
  457.  
  458.         2)  The "adjust" instructions which help in performing arithmetic
  459.             on ASCII or packed decimal data
  460.  
  461.         3)  The shift and rotate instructions.  These have a restriction on
  462.             the second operand:  it must either be the immediate value 1 or
  463.             the contents of the CL register.
  464.  
  465.         4)  IN and OUT which send or receive data from one of the 1024
  466.             hardware ports.
  467.  
  468.         5)  CBW and CWD -- convert byte to word or word to doubleword by
  469.             sign extension
  470.  
  471.     d.  Flow of control instructions.  These deserve study in themselves
  472.         and we will discuss them a little more.  They include
  473.  
  474.         1)  CALL, RET -- call and return
  475.  
  476.         2)  INT, IRET -- interrupt and return-from-interrupt
  477.  
  478.         3)  JMP -- jump or "branch"
  479.  
  480.         4)  LOOP, LOOPNZ, LOOPZ -- special (and useful) instructions which
  481.             implement a counted loop similar to the 370 BCT instruction
  482.  
  483.         5)  various conditional jump instructions
  484.  
  485.     e.  String instructions.  These implement a limited storage-to-storage
  486.         instruction subset and are quite powerful.  All of them have the
  487.         property that
  488.  
  489.         1)  The source of data is described by the combination DS and SI.
  490.  
  491.         2)  The destination of data is described by the combination ES and
  492.             DI.
  493.  
  494.         3)  As part of the operation, the SI and/or DI register(s) is(are)
  495.             incremented or decremented so the operation can be repeated.
  496.  
  497.  
  498.  
  499. IBM PC Assembly Language Tutorial                                         8
  500.  
  501.  
  502.  
  503.         They include
  504.  
  505.         1)  CMPSB/CMPSW -- compare byte or word
  506.  
  507.         2)  LODSB/LODSW -- load byte or word into AL or AX
  508.  
  509.         3)  STOSB/STOSW -- store byte or word from AL or AX
  510.  
  511.         4)  MOVSB/MOVSW -- move byte or word
  512.  
  513.         5)  SCASB/SCASW -- compare byte or word with contents of AL or AX
  514.  
  515.         6)  REP/REPE/REPNE -- a prefix which can be combined with any of
  516.             the above instructions to make them execute repeatedly across a
  517.             string of data whose length is held in CX.
  518.  
  519.     f.  Flag instructions: CLI, STI, CLD, STD, CLC, STC.  These can set or
  520.         clear the interrupt (enabled) direction (for string operations) or
  521.         carry flags.
  522.  
  523.     The addressing summary and the instruction summary given above masks a
  524.     lot of annoying little exceptions.  For example, you can't POP CS, and
  525.     although the R <-- M form of LES is legal, the M <-- R form isn't etc.
  526.     etc.  My advice is
  527.  
  528.     a.  Go for the general rules
  529.  
  530.     b.  Don't try to memorize the exceptions
  531.  
  532.     c.  Rely on common sense and the assembler to teach you about
  533.         exceptions over time.  A lot of the exceptions cover things you
  534.         wouldn't want to do anyway.
  535.  
  536. 5.  A few instructions are rich enough and useful enough to warrent careful
  537.     study.  Here are a few final study guidelines:
  538.  
  539.     a.  It is well worth the time learning to use the string instruction
  540.         set effectively.  Among the most useful are
  541.  
  542.                 REP MOVSB           ;moves a string
  543.                 REP STOSB           ;initializes memory
  544.                 REPNE SCASB         ;look up occurance of character in string
  545.                 REPE CMPSB          ;compare two strings
  546.  
  547.     b.  Similarly, if you have never written for a stack machine before,
  548.         you will need to exercise PUSH and POP and get very comfortable
  549.         with them because they are going to be good friends.  If you are
  550.         used to the 370, with lots of general purpose registers, you may
  551.         find yourself feeling cramped at first, with many fewer registers
  552.         and many instructions having register restrictions.  But, you have
  553.         a hidden ally:  you need a register and you don't want to throw
  554.         away what's in it?  Just PUSH it, and when you are done, POP it
  555.         back.  This can lead to abuse.  Never have more than two
  556.         "expedient" PUSHes in effect and never leave something PUSHed
  557.         across a major header comment or for more than 15 instructions or
  558.  
  559.  
  560. IBM PC Assembly Language Tutorial                                         9
  561.  
  562.  
  563.  
  564.         so.  An exception is the saving and restoring of registers at
  565.         entrance to and exit from a subroutine; here, if the subroutine is
  566.         long, you should probably PUSH everything which the caller may need
  567.         saved, whether you will use the register or not, and POP it in
  568.         reverse order at the end.
  569.  
  570.         Be aware that CALL and INT push return address information on the
  571.         stack and RET and IRET pop it off.  It is a good idea to become
  572.         familiar with the structure of the stack.
  573.  
  574.     c.  In practice, to invoke system services you will use the INT
  575.         instruction.  It is quite possible to use this instruction effec-
  576.         tively in a cookbook fashion without knowing precisely how it
  577.         works.
  578.  
  579.     d.  The transfer of control instructions (CALL, RET, JMP) deserve care-
  580.         ful study to avoid confusion.  You will learn that these can be
  581.         classified as follows:
  582.  
  583.         1)  all three have the capability of being either NEAR (CS register
  584.             unchanged) or FAR (CS register changed)
  585.  
  586.         2)  JMPs and CALLs can be DIRECT (target is assembled into instruc-
  587.             tion) or INDIRECT (target fetched from memory or register)
  588.  
  589.         3)  if NEAR and DIRECT, a JMP can be SHORT (less than 128 bytes
  590.             away) or LONG
  591.  
  592.         In general, the third issue is not worth worrying about.  On a for-
  593.         ward jump which is clearly VERY short, you can tell the assembler
  594.         it is short and save one byte of code:
  595.  
  596.                    JMP SHORT  CLOSEBY
  597.  
  598.         On a backward jump, the assembler can figure it out for you.  On a
  599.         forward jump of dubious length, let the assembler default to a LONG
  600.         form; at worst you waste one byte.
  601.  
  602.         Also leave the assembler to worry about how the target address is
  603.         to be represented, in absolute form or relative form.
  604.  
  605.     e.  The conditional jump set is rather confusing when studied apart
  606.         from the assembler, but you do need to get a feeling for it.  The
  607.         interactions of the sign, carry, and overflow flags can get your
  608.         mind stuttering pretty fast if you worry about it too much.  What
  609.         is boils down to, though, is
  610.  
  611.                 JZ        means what it says
  612.                 JNZ       means what it says
  613.                 JG reater this means "if the SIGNED difference is positive"
  614.                 JA bove   this means "if the UNSIGNED difference is positive"
  615.                 JL ess    this means "if the SIGNED difference is negative"
  616.                 JB elow   this means "if the UNSIGNED difference is negative"
  617.                 JC arry   assembles the same as JB; it's an aesthetic choice
  618.  
  619.  
  620.  
  621. IBM PC Assembly Language Tutorial                                        10
  622.  
  623.  
  624.  
  625.         You should understand that all conditional jumps are inherently
  626.         DIRECT, NEAR, and "short"; the "short" part means that they can't
  627.         go more than 128 bytes in either direction.  Again, this is some-
  628.         thing you could easily imagine to be more of a problem than it is.
  629.         I follow this simple approach:
  630.  
  631.         1)  When taking an abnormal exit from a block of code, I always use
  632.             an unconditional jump.  Who knows how far you are going to end
  633.             up jumping by the time the program is finished.  For example, I
  634.             wouldn't code this:
  635.  
  636.                    TEST     AL,IDIBIT       ;Is the idiot bit on?
  637.                    JNZ      OYVEY           ;Yes.  Go to general cleanup
  638.  
  639.             Rather, I would probably code this:
  640.  
  641.                    TEST     AL,IDIBIT       ;Is the idiot bit on?
  642.                    JZ       NOIDIOCY        ;No.  I am saved.
  643.                    JMP      OYVEY           ;Yes.  What can we say...
  644.               NOIDIOCY:
  645.  
  646.             The latter, of course, is a jump around a jump.  Some would say
  647.             it is evil, but I submit it is hard to avoid in this language.
  648.  
  649.         2)  Otherwise, within a block of code, I use conditional jumps
  650.             freely.  If the block eventually grows so long that the assem-
  651.             bler starts complaining that my conditional jumps are too long
  652.             I
  653.  
  654.             a)  consider reorganizing the block but
  655.  
  656.             b)  also consider changing some conditional jumps to their
  657.                 opposite and use the "jump around a jump" approach as shown
  658.                 above.
  659.  
  660.     Enough about specific instructions!
  661.  
  662. 6.  Finally, in order to use the assembler effectively, you need to know
  663.     the default rules for which segment registers are used to complete
  664.     addresses in which situations.
  665.  
  666.     a.  CS is used to complete an address which is the target of a NEAR
  667.         DIRECT jump.  On an NEAR INDIRECT jump, DS is used to fetch the
  668.         address from memory but then CS is used to complete the address
  669.         thus fetched.  On FAR jumps, of course, CS is itself altered.  The
  670.         instruction counter is always implicitly pointing in the code seg-
  671.         ment.
  672.  
  673.     b.  SS is used to complete an address if BP is used in its formation.
  674.         Otherwise, DS is always used to complete a data address.
  675.  
  676.     c.  On the string instructions, the target is always formed from ES and
  677.         DI.  The source is normally formed from DS and SI.  If there is a
  678.         segment prefix, it overrides the source not the target.
  679.  
  680.  
  681.  
  682. IBM PC Assembly Language Tutorial                                        11
  683.  
  684.  
  685.  
  686. Learning about DOS
  687. __________________
  688. Learning about DOS
  689. Learning about DOS
  690. Learning about DOS
  691.  
  692.  
  693. I think the best way to learn about DOS internals is to read the technical
  694. appendices in the manual.  These are not as complete as we might wish, but
  695. they really aren't bad; I certainly have learned a lot from them.  What you
  696. don't learn from them you might eventually learn via judicious disassembly
  697. of parts of DOS, but that shouldn't really be necessary.
  698.  
  699. From reading the technical appendices, you learn that interrupts 20H
  700. through 27H are used to communicate with DOS.  Mostly, you will use inter-
  701. rupt 21H, the DOS function manager.
  702.  
  703. The function manager implements a great many services.  You request the
  704. individual services by means of a function code in the AH register.  For
  705. example, by putting a nine in the AH register and issuing interrupt 21H you
  706. tell DOS to print a message on the console screen.
  707.  
  708. Usually, but by no means always, the DX register is used to pass data for
  709. the service being requested.  For example, on the print message service
  710. just mentioned, you would put the 16 bit address of the message in the DX
  711. register.  The DS register is also implicitly part of this argument, in
  712. keeping with the universal segmentation rules.
  713.  
  714. In understanding DOS functions, it is useful to understand some history and
  715. also some of the philosophy of MS-DOS with regard to portability.  General-
  716. ly, you will find, once you read the technical information on DOS and also
  717. the IBM technical reference, you will know more than one way to do almost
  718. anything.  Which is best?  For example, to do asynch adapter I/O, you can
  719. use the DOS calls (pretty incomplete), you can use BIOS, or you can go
  720. directly to the hardware.  The same thing is true for most of the other
  721. primitive I/O (keyboard or screen) although DOS is more likely to give you
  722. added value in these areas.  When it comes to file I/O, DOS itself offers
  723. more than one interface.  For example, there are four calls which read data
  724. from a file.
  725.  
  726. The way to decide rationally among these alternatives is by understanding
  727. the tradeoffs of functionality versus portability.  Three kinds of porta-
  728. bility need to be considered:  machine portability, operating system porta-
  729. bility (for example, the ability to assemble and run code under CP/M 86)
  730. and DOS version portability (the ability for a program to run under older
  731. versions of DOS>.
  732.  
  733. Most of the functions originally offered in DOS 1.0 were direct descendents
  734. of CP/M functions; there is even a compatibility interface so that programs
  735. which have been translated instruction for instruction from 8080 assembler
  736. to 8086 assembler might have a reasonable chance of running if they use
  737. only the core CP/M function set.  Among the most generally useful in this
  738. original compatibility set are
  739.  
  740.  
  741.  
  742.  
  743.  
  744.  
  745.  
  746.  
  747. IBM PC Assembly Language Tutorial                                        12
  748.  
  749.  
  750.  
  751.   09   --  print a full message on the screen
  752.   0A   --  get a console input line with full DOS editing
  753.   0F   --  open a file
  754.   10   --  close a file (really needed only when writing)
  755.   11   --  find first file matching a pattern
  756.   12   --  find next file matching a pattern
  757.   13   --  erase a file
  758.   16   --  create a file
  759.   17   --  rename a file
  760.   1A   --  set disk transfer address
  761.  
  762. The next set provide no function above what you can get with BIOS calls or
  763. more specialized DOS calls.  However, they are preferable to BIOS calls
  764. when portability is an issue.
  765.  
  766.   00   --  terminate execution
  767.   01   --  read keyboard character
  768.   02   --  write screen character
  769.   03   --  read COM port character
  770.   04   --  write COM port character
  771.   05   --  print a character
  772.   06   --  read keyboard or write screen with no editing
  773.  
  774. The standard file I/O calls are inferior to the specialized DOS calls but
  775. have the advantage of making the program easier to port to CP/M style sys-
  776. tems.  Thus they are worth mentioning:
  777.  
  778.   14   --  sequential read from file
  779.   15   --  sequential write to file
  780.   21   --  random read from file
  781.   22   --  random write to file
  782.   23   --  determine file size
  783.   24   --  set random record
  784.  
  785. In addition to the CP/M compatible services, DOS also offers some special-
  786. ized services which have been available in all releases of DOS.  These
  787. include
  788.  
  789.   27   --  multi-record random read.
  790.   28   --  multi-record random write.
  791.   29   --  parse filename
  792.   2A-2D -- get and set date and time
  793.  
  794. All of the calls mentioned above which have anything to do with files make
  795. use of a data area called the "FILE CONTROL BLOCK" (FCB).  The FCB is any-
  796. where from 33 to 37 bytes long depending on how it is used.  You are
  797. responsible for creating an FCB and filling in the first 12 bytes, which
  798. contain a drive code, a file name, and an extension.
  799.  
  800. When you open the FCB, the system fills in the next 20 bytes, which
  801. includes a logical record length.  The initial lrecl is always 128 bytes,
  802. to achieve CP/M compatibility.  The system also provides other useful
  803. information such as the file size.
  804.  
  805.  
  806.  
  807.  
  808. IBM PC Assembly Language Tutorial                                        13
  809.  
  810.  
  811.  
  812. After you have opened the FCB, you can change the logical record length.
  813. If you do this, your program is no longer CP/M compatible, but that doesn't
  814. make it a bad thing to do.  DOS documentation suggests you use a logical
  815. record length of one for maximum flexibility.  This is usually a good
  816. recommendation.
  817.  
  818. To perform actual I/O to a file, you eventually need to fill in byte 33 or
  819. possibly bytes 34-37 of the FCB.  Here you supply information about the
  820. record you are interested in reading or writing.  For the most part, this
  821. part of the interface is compatible with CP/M.
  822.  
  823. In general, you do not need to (and should not) modify other parts of the
  824. FCB.
  825.  
  826. The FCB is pretty well described in appendix E of the DOS manual.
  827.  
  828. Beginning with DOS 2.0, there is a whole new system of calls for managing
  829. files which don't require that you build an FCB at all.  These calls are
  830. quite incompatible with CP/M and also mean that your program cannot run
  831. under older releases of DOS.  However, these calls are very nice and easy
  832. to use.  They have these characteristics
  833.  
  834. 1.  To open, create, delete, or rename a file, you need only a character
  835.     string representing its name.
  836.  
  837. 2.  The open and create calls return a 16 bit value which is simply placed
  838.     in the BX register on subsequent calls to refer to the file.
  839.  
  840. 3.  There is not a separate call required to specify the data buffer.
  841.  
  842. 4.  Any number of bytes can be transfered on a single call; no data area
  843.     must be manipulated to do this.
  844.  
  845. The "new" DOS calls also include comprehensive functions to manipulate the
  846. new chained directory structure and to allocate and free memory.
  847.  
  848.  
  849.  
  850. Learning the assembler
  851. ______________________
  852. Learning the assembler
  853. Learning the assembler
  854. Learning the assembler
  855.  
  856.  
  857. It is my feeling that many people can teach themselves to use the assembler
  858. by reading the MACRO Assembler manual if
  859.  
  860. 1.  You have read and understood a book like Morse and thus have a feeling
  861.     for the instruction set
  862.  
  863. 2.  You know something about DOS services and so can communicate with the
  864.     keyboard and screen and do something marginally useful with files.  In
  865.     the absence of this kind of knowledge, you can't write meaningful prac-
  866.     tice programs and so will not progress.
  867.  
  868. 3.  You have access to some good examples (the ones supplied with the
  869.     assembler are not good, in my opinion.  I will try to supply you with
  870.     some more relevant ones.
  871.  
  872.  
  873. IBM PC Assembly Language Tutorial                                        14
  874.  
  875.  
  876.  
  877. 4.  You ignore the things which are most confusing and least useful.  Some
  878.     of the most confusing aspects of the assembler include the facilities
  879.     combining segments.  But, you can avoid using all but the simplest of
  880.     these facilities in many cases, even while writing quite substantial
  881.     applications.
  882.  
  883. 5.  The easiest kind of assembler program to write is a COM program.  They
  884.     might seem harder, at first, then EXE programs because there is an
  885.     extra step involved in creating the executable file, but COM programs
  886.     are structurally very much simpler.
  887.  
  888. At this point, it is necessary to talk about COM programs and EXE programs.
  889. As you probably know, DOS supports two kinds of executable files.  EXE pro-
  890. grams are much more general, can contain many segments, and are generally
  891. built by compilers and sometimes by the assembler.  If you follow the lead
  892. given by the samples distributed with the assembler, you will end up with
  893. EXE programs.  A COM program, in contrast, always contains just one
  894. segment, and receives control with all four segment registers containing
  895. the same value.  A COM program, thus, executes in a simplified environment,
  896. a 64K address space.  You can go outside this address space simply by tem-
  897. porarily changing one segment register, but you don't have to, and that is
  898. the thing which makes COM programs nice and simple.  Let's look at a very
  899. simple one.
  900.  
  901. The classic text on writing programs for the C language says that the first
  902. thing you should write is a program which says
  903.  
  904.       HELLO, WORLD.
  905.  
  906. when invoked.  What's sauce for C is sauce for assembler, so let's start
  907. with a HELLO program of our own.  My first presentation of this will be
  908. bare bones, not stylistically complete, but just an illustration of what an
  909. assembler program absolutely has to have:
  910.  
  911. HELLO  SEGMENT                  ;Set up HELLO code and data section
  912.        ASSUME CS:HELLO,DS:HELLO ;Tell assembler about conditions at entry
  913.        ORG  100H                ;A .COM program begins with 100H byte prefix
  914. MAIN:  JMP  BEGIN               ;Control must start here
  915. MSG    DB   'Hello, world.$'    ;But it is generally useful to put data first
  916. BEGIN: MOV  DX,OFFSET MSG       ;Let DX --> message.
  917.        MOV  AH,9                ;Set DOS function code for printing a message
  918.        INT  21H                 ;Invoke DOS
  919.        RET                      ;Return to system
  920. HELLO  ENDS                     ;End of code and data section
  921.         END  MAIN                 ;Terminate assembler and specify entry point
  922.  
  923.  
  924. First, let's attend to some obvious points.  The macro assembler uses the
  925. general form
  926.  
  927.    name    opcode    operands
  928.  
  929. Unlike the 370 assembler, though, comments are NOT set off from operands by
  930. blanks.  The syntax uses blanks as delimiters within the operand field (see
  931. line 6 of the example) and so all comments must be set off by semi-colons.
  932.  
  933.  
  934. IBM PC Assembly Language Tutorial                                        15
  935.  
  936.  
  937.  
  938. Line comments are frequently set off with a semi-colon in column 1.  I use
  939. this approach for block comments too, although there is a COMMENT statement
  940. which can be used to introduce a block comment.
  941.  
  942. Being an old 370 type, I like to see assembler code in upper case, although
  943. my comments are mixed case.  Actually, the assembler is quite happy with
  944. mixed case anywhere.
  945.  
  946. As with any assembler, the core of the opcode set consists of opcodes which
  947. generate machine instructions but there are also opcodes which generate
  948. data and ones which function as instructions to the assembler itself, some-
  949. times called pseudo-ops.  In the example, there are five lines which gener-
  950. ate machine code (JMP, MOV, MOV, INT, RET), one line which generates data
  951. (DB) and five pseudo-ops (SEGMENT, ASSUME, ORG, ENDS, and END).
  952.  
  953. We will discuss all of them.
  954.  
  955. Now, about labels.  You will see that some labels in the example end in a
  956. colon and some don't.  This is just a bit confusing at first, but no real
  957. mystery.  If a label is attached to a piece of code (as opposed to data),
  958. then the assembler needs to know what to do when you JMP to or CALL that
  959. label.  By convention, if the label ends in a colon, the assembler will use
  960. the NEAR form of JMP or CALL.  If the label does not end in a colon, it
  961. will use the FAR form.  In practice, you will always use the colon on any
  962. label you are jumping to inside your program because such jumps are always
  963. NEAR; there is no reason to use a FAR jump within a single code section.  I
  964. mention this, though, because leaving off the colon isn't usually trapped
  965. as a syntax error, it will generally cause something more abstruse to go
  966. wrong.
  967.  
  968. On the other hand, a label attached to a piece of data or a pseudo-op never
  969. ends in a colon.
  970.  
  971. Machine instructions will generally take zero, one or two operands.  Where
  972. there are two operands, the one which receives the result goes on the left
  973. as in 370 assembler.
  974.  
  975. I tried to explain this before, now maybe it will be even clearer:  there
  976. are many more 8086 machine opcodes then there are assembler opcodes to rep-
  977. resent them.  For example, there are five kinds of JMP, four kinds of CALL,
  978. two kinds of RET, and at least five kinds of MOV depending on how you count
  979. them.  The macro assembler makes a lot of decisions for you based on the
  980. form taken by the operands or on attributes assigned to symbols elsewhere
  981. in your program.  In the example above, the assembler will generate the
  982. NEAR DIRECT form of JMP because the target label BEGIN labels a piece of
  983. code instead of a piece of data (this makes the JMP DIRECT) and ends in a
  984. colon (this makes the JMP NEAR).  The assembler will generate the immediate
  985. forms of MOV because the form OFFSET MSG refers to immediate data and
  986. because 9 is a constant.  The assembler will generate the NEAR form of RET
  987. because that is the default and you have not told it otherwise.
  988.  
  989. The DB (define byte) pseudo-op is an easy one:  it is used to put one or
  990. more bytes of data into storage.  There is also a DW (define word)
  991. pseudo-op and a  DD (define doubleword) pseudo-op;  in the PC MACRO assem-
  992. bler, the fact that a label refers to a byte of storage, a word of storage,
  993.  
  994.  
  995. IBM PC Assembly Language Tutorial                                        16
  996.  
  997.  
  998.  
  999. or a doubleword of storage can be very significant in ways which we will
  1000. see presently.
  1001.  
  1002. About that OFFSET operator, I guess this is the best way to make the point
  1003. about how the assembler decides what instruction to assemble:  an analogy
  1004. with 370 assembler:
  1005.  
  1006.   PLACE    DC   ......
  1007.            ...
  1008.            LA   R1,PLACE
  1009.            L    R1,PLACE
  1010.  
  1011. In 370 assembler, the first instruction puts the address of label PLACE in
  1012. register 1, the second instruction puts the contents of storage at label
  1013. PLACE in register 1.  Notice that two different opcodes are used.  In the
  1014. PC assembler, the analogous instructions would be
  1015.  
  1016.   PLACE    DW   ......
  1017.            ...
  1018.            MOV  DX,OFFSET PLACE
  1019.            MOV  DX,PLACE
  1020.  
  1021. If PLACE is the label of a word of storage, then the second instruction
  1022. will be understood as a desire to fetch that data into DX.  If X is a
  1023. label, then "OFFSET X" means "the ordinary number which represents X's off-
  1024. set from the start of the segment."  And, if the assembler sees an ordinary
  1025. number, as opposed to a label, it uses the instruction which is equivalent
  1026. to LA.
  1027.  
  1028. If PLACE were the label of a DB pseudo-op, instead of a DW, then
  1029.  
  1030.            MOV  DX,PLACE
  1031.  
  1032. would be illegal.  The assembler worries about length attributes of its
  1033. operands.
  1034.  
  1035. Next, numbers and constants in general.  The assembler's default radix is
  1036. decimal.  You can change this, but I don't recommend it.  If you want to
  1037. represent numbers in other forms of notation such as hex or bit, you gener-
  1038. ally use a trailing letter.  For example,
  1039.  
  1040.            21H
  1041.   is hexidecimal 21,
  1042.            00010000B
  1043.   is the eight bit binary number pictured.
  1044.  
  1045. The next elements we should point to are the SEGMENT...ENDS pair and the
  1046. END instruction.  Every assembler program has to have these elements.
  1047.  
  1048. SEGMENT tells the assembler you are starting a section of contiguous mate-
  1049. rial (code and/or data).  The symmetrically named ENDS statement tells the
  1050. assembler you are finished with a section of contiguous material.  I wish
  1051. they didn't use the word SEGMENT in this context.  To me, a "segment" is a
  1052. hardware construct:  it is the 64K of real storage which becomes address-
  1053. able by virtue of having a particular value in a segment register.  Now, it
  1054.  
  1055.  
  1056. IBM PC Assembly Language Tutorial                                        17
  1057.  
  1058.  
  1059.  
  1060. is true that the "segments" you make with the assembler often correspond to
  1061. real hardware "segments" at execution time.  But, if you look at things
  1062. like the GROUP and CLASS options supported by the linker, you will discover
  1063. that this correspondence is by no means exact.  So, at risk of maybe con-
  1064. fusing you even more, I am going to use the more informal term "section" to
  1065. refer to the area set off by means of the SEGMENT and ENDS instructions.
  1066.  
  1067. The sections delimited by SEGMENT...ENDS pairs are really a lot like CSECTs
  1068. and DSECTs in the 370 world.
  1069.  
  1070. I strongly recommend that you be selective in your study of the SEGMENT
  1071. pseudo-op as described in the manual.  Let me just touch on it here.
  1072.  
  1073.   name     SEGMENT
  1074.   name     SEGMENT  PUBLIC
  1075.   name     SEGMENT  AT  nnn
  1076.  
  1077. Basically, you can get away with just the three forms given above.  The
  1078. first form is what you use when you are writing a single section of assem-
  1079. bler code which will not be combined with other pieces of code at link
  1080. time.   The second form says that this assembly only contains part of the
  1081. section;  other parts might be assembled separately and combined later by
  1082. the linker.
  1083.  
  1084. I have found that one can construct reasonably large modular applications
  1085. in assembler by simply making every assembly use the same segment name and
  1086. declaring the name to be PUBLIC each time.  If you read the assembler and
  1087. linker documentation, you will also be bombarded by information about more
  1088. complex options such as the GROUP statement and the use of other "combine
  1089. types" and "classes."  I don't recommend getting into any of that.  I will
  1090. talk more about the linker and modular construction of programs a little
  1091. later.  The assembler manual also implies that a STACK segment is required.
  1092. This is not really true.  There are numerous ways to assure that you have a
  1093. valid stack at execution time.
  1094.  
  1095. Of course, if you plan to write applications in assembler which are more
  1096. than 64K in size, you will need more than what I have told you; but who is
  1097. really going to do that?  Any application that large is likely to be coded
  1098. in a higher level language.
  1099.  
  1100. The third form of the SEGMENT statement makes the delineated section into
  1101. something like a "DSECT;" that is, it doesn't generate any code, it just
  1102. describes what is present somewhere already in the computer's memory.
  1103. Sometimes the AT value you give is meaningful.  For example, the BIOS work
  1104. area is located at location 40 hex.  So, you might see
  1105.  
  1106.   BIOSAREA  SEGMENT AT 40H      ;Map BIOS work area
  1107.             ORG  BIOSAREA+10H
  1108.   EQUIP     DB   ?              ;Location of equipment flags, first byte
  1109.   BIOSAREA  ENDS
  1110.  
  1111. in a program which was interested in mucking around in the BIOS work area.
  1112.  
  1113. At other times, the AT value you give may be arbitrary, as when you are
  1114. mapping a repeated control block:
  1115.  
  1116.  
  1117. IBM PC Assembly Language Tutorial                                        18
  1118.  
  1119.  
  1120.  
  1121.   PROGPREF SEGMENT   AT 0      ;Really a DSECT mapping the program prefix
  1122.            ORG   PROGPREF+6
  1123.   MEMSIZE  DW   ?              ;Size of available memory
  1124.   PROGPREF ENDS
  1125.  
  1126. Really, no matter whether the AT value represents truth or fiction, it is
  1127. your responsibility, not the assembler's, to get set up a segment register
  1128. so that you can really reach the storage in question.   So, you can't say
  1129.  
  1130.          MOV  AL,EQUIP
  1131.  
  1132. unless you first say something like
  1133.  
  1134.          MOV  AX,BIOSAREA   ;BIOSAREA becomes a symbol with value 40H
  1135.          MOV  ES,AX
  1136.          ASSUME ES:BIOSAREA
  1137.  
  1138. Enough about SEGMENT.  The END statement is simple.  It goes at the end of
  1139. every assembly.  When you are assembling a subroutine, you just say
  1140.  
  1141.          END
  1142.  
  1143. but when you are assembling the main routine of a program you say
  1144.  
  1145.         END label
  1146.  
  1147. where 'label' is the place where execution is to begin.
  1148.  
  1149. Another pseudo-op illustrated in the program is ASSUME.  ASSUME is like the
  1150. USING statement in 370 assembler.  However, ASSUME can ONLY refer to seg-
  1151. ment registers.  The assembler uses ASSUME information to decide whether to
  1152. assemble segment override prefixes and to check that the data you are try-
  1153. ing to access is really accessible.  In this case, we can reassure the
  1154. assembler that both the CS and DS registers will address the section called
  1155. HELLO at execution time.  Actually, the SS and ES registers will too, but
  1156. the assembler never needs to make use of this information.
  1157.  
  1158. I guess I have explained everything in the program except that ORG
  1159. pseudo-op.  ORG means the same thing as it does in many assembly languages.
  1160. It tells the assembler to move its location counter to some particular
  1161. address.  In this case, we have asked the assembler to start assembling
  1162. code hex 100 bytes from the start of the section called HELLO instead of at
  1163. the very beginning.  This simply reflects the way COM programs are loaded.
  1164. When a COM program is loaded by the system, the system sets up all four
  1165. segment registers to address the same 64K of storage.  The first 100 hex
  1166. bytes of that storage contains what is called the program prefix; this area
  1167. is described in appendix E of the DOS manual.  Your COM program physically
  1168. begins after this.  Execution begins with the first physical byte of your
  1169. program; that is why the JMP instruction is there.
  1170.  
  1171. Wait a minute, you say, why the JMP instruction at all?  Why not put the
  1172. data at the end?  Well, in a simple program like this I probably could have
  1173. gotten away with that.  However, I have the habit of putting data first and
  1174. would encourage you to do the same because of the way the assembler has of
  1175. assembling different instructions depending on the nature of the operand.
  1176.  
  1177.  
  1178. IBM PC Assembly Language Tutorial                                        19
  1179.  
  1180.  
  1181.  
  1182. Unfortunately, sometimes the different choices of instruction which can
  1183. assemble from a single opcode have different lengths.  If the assembler has
  1184. already seen the data when it gets to the instructions it has a good chance
  1185. of reserving the right number of bytes on the first pass.  If the data is
  1186. at the end, the assembler may not have enough information on the first pass
  1187. to reserve the right number of bytes for the instruction.  Sometimes the
  1188. assembler will complain about this, something like "Forward reference is
  1189. illegal" but at other times, it will make some default assumption.  On the
  1190. second pass, if the assumption turned out to be wrong, it will report what
  1191. is called a "Phase error," a very nasty error to track down.  So get in the
  1192. habit of putting data and equated symbols ahead of code.
  1193.  
  1194. OK.  Maybe you understand the program now.  Let's walk through the steps
  1195. involved in making it into a real COM file.
  1196.  
  1197. 1.  The file should be created with the name HELLO.ASM (actually the name
  1198.     is arbitrary but the extension .ASM is conventional and useful)
  1199.  
  1200. 2.
  1201.  
  1202.       ASM   HELLO,,;
  1203.  
  1204.     (this is just one example of invoking the assembler; it uses the small
  1205.     assembler ASM, it produces an object file and a listing file with the
  1206.     same name as the source file.  I am not going exhaustively into how to
  1207.     invoke the assembler, which the manual goes into pretty well.  I guess
  1208.     this is the first time I mentioned that there are really two
  1209.     assemblers; the small assembler ASM will run in a 64K machine and
  1210.     doesn't support macros.  I used to use it all the time; now that I have
  1211.     a bigger machine and a lot of macro libraries I use the full function
  1212.     assembler MASM.  You get both when you buy the package).
  1213.  
  1214. 3.  If you issue DIR at this point, you will discover that you have
  1215.     acquired HELLO.OBJ (the object code resulting from the assembly) and
  1216.     HELLO.LST (a listing file).  I guess I can digress for a second here
  1217.     concerning the listing file.  It contains TAB characters.  I have found
  1218.     there are two good ways to get it printed and one bad way.  The bad way
  1219.     is to use LPT1: as the direct target of the listing file or to try
  1220.     copying the LST file to LPT1 without first setting the tabs on the
  1221.     printer.  The two good ways are to either
  1222.  
  1223.     a.  direct it to the console and activate the printer with CTRL-PRTSC.
  1224.         In this case, DOS will expand the tabs for you.
  1225.  
  1226.     b.  direct to LPT1: but first send the right escape sequence to LPT1 to
  1227.         set the tabs every eight columns.  I have found that on some early
  1228.         serial numbers of the IBM PC printer, tabs don't work quite right,
  1229.         which forces you to the first option.
  1230.  
  1231. 4.
  1232.  
  1233.           LINK  HELLO;
  1234.  
  1235.     (again, there are lots of linker options but this is the simplest.  It
  1236.     takes HELLO.OBJ and makes HELLO.EXE).  HELLO.EXE?  I thought we were
  1237.  
  1238.  
  1239. IBM PC Assembly Language Tutorial                                        20
  1240.  
  1241.  
  1242.  
  1243.     making a COM program, not an EXE program.  Right.  HELLO.EXE isn't
  1244.     really executable; its just that the linker doesn't know about COM pro-
  1245.     grams.  That requires another utility.  You don't have this utility if
  1246.     you are using DOS 1.0; you have it if you are using DOS 1.1 or DOS 2.0.
  1247.     Oh, by the way, the linker will warn you that you have no stack
  1248.     segment.  Don't worry about it.
  1249.  
  1250. 5.
  1251.  
  1252.           EXE2BIN  HELLO HELLO.COM
  1253.  
  1254.     This is the final step.  It produces the actual program you will exe-
  1255.     cute.  Note that you have to spell out HELLO.COM; for a nominally
  1256.     rational but actually perverse reason, EXE2BIN uses the default exten-
  1257.     sion BIN instead of COM for its output file.  At this point, you might
  1258.     want to erase HELLO.EXE; it looks a lot more useful than it is.
  1259.     Chances are you won't need to recreate HELLO.COM unless you change the
  1260.     source and then you are going to have to redo the whole thing.
  1261.  
  1262. 6.
  1263.  
  1264.           HELLO
  1265.  
  1266.     You type hello, that invokes the program, it says
  1267.  
  1268.           HELLO YOURSELF!!!
  1269.  
  1270.     (oops, what did I do wrong....?)
  1271.  
  1272.  
  1273.  
  1274. What about subroutines?
  1275. _______________________
  1276. What about subroutines?
  1277. What about subroutines?
  1278. What about subroutines?
  1279.  
  1280.  
  1281. I started with a simple COM program because I actually think they are easi-
  1282. er to create than subroutines to be called from high level languages, but
  1283. maybe its really the latter you are interested in.  Here, I think you
  1284. should get comfortable with the assembler FIRST with little exercises like
  1285. the one above and also another one which I will finish up with.
  1286.  
  1287. Next you are ready to look at the interface information for your particular
  1288. language.  You usually find this in some sort of an appendix.  For example,
  1289. the BASIC manual has Appendix C on Machine Language Subroutines.  The
  1290. PASCAL manual buries the information a little more deeply:  the interface
  1291. to a separately compiled routine can be found in the Chapter on Procedures
  1292. and Functions, in a subsection called Internal Calling Conventions.
  1293.  
  1294. Each language is slightly different, but here are what I think are some
  1295. common issues in subroutine construction.
  1296.  
  1297. 1.  NEAR versus FAR?  Most of the time, your language will probably call
  1298.     your assembler routine as a FAR routine.  In this case, you need to
  1299.     make sure the assembler will generate the right kind of return.  You do
  1300.     this with a PROC...ENDP statement pair.  The PROC statement is probably
  1301.  
  1302.  
  1303.  
  1304. IBM PC Assembly Language Tutorial                                        21
  1305.  
  1306.  
  1307.  
  1308.     a good idea for a NEAR routine too even though it is not strictly
  1309.     required:
  1310.  
  1311.               FAR linkage:        |            NEAR linkage:
  1312.                                   |
  1313.     ARBITRARY SEGMENT             |  SPECIFIC  SEGMENT  PUBLIC
  1314.               PUBLIC THENAME      |            PUBLIC THENAME
  1315.               ASSUME CS:ARBITRARY |            ASSUME CS:SPECIFIC,DS:SPECIFIC
  1316.     THENAME   PROC FAR            |            ASSUME ES:SPECIFIC,SS:SPECIFIC
  1317.               ..... code and data |  THENAME   PROC NEAR
  1318.     THENAME   ENDP                |            ..... code and data ....
  1319.     ARBITRARY ENDS                |  THENAME   ENDP
  1320.               END                 |  SPECIFIC  ENDS
  1321.                                   |            END
  1322.  
  1323.  
  1324.     With FAR linkage, it doesn't really matter what you call the segment.
  1325.     you must declare the name by which you will be called in a PUBLIC pseu-
  1326.     do-op and also show that it is a FAR procedure.  Only CS will be ini-
  1327.     tialized to your segment when you are called.  Generally, the other
  1328.     segment registers will continue to point to the caller's segments.
  1329.  
  1330.     With NEAR linkage, you are executing in the same segment as the caller.
  1331.     Therefore, you must give the segment a specific name as instructed by
  1332.     the language manual.  However, you may be able to count on all segment
  1333.     registers pointing to your own segment (sometimes the situation can be
  1334.     more complicated but I cannot really go into all of the details).  You
  1335.     should be aware that the code you write will not be the only thing in
  1336.     the segment and will be physically relocated within the segment by the
  1337.     linker.  However, all OFFSET references will be relocated and will be
  1338.     correct at execution time.
  1339.  
  1340. 2.  Parameters passed on the stack.  Usually, high level languages pass
  1341.     parameters to subroutines by pushing words onto the stack prior to
  1342.     calling you.  What may differ from language to language is the nature
  1343.     of what is pushed (OFFSET only or OFFSET and SEGMENT) and the order in
  1344.     which it is pushed (left to right, right to left within the CALL state-
  1345.     ment).  However, you will need to study the examples to figure out how
  1346.     to retrieve the parameters from the stack.  A useful fact to exploit is
  1347.     the fact that a reference involving the BP register defaults to a ref-
  1348.     erence to the stack segment.  So, the following strategy can work:
  1349.  
  1350.       ARGS     STRUC
  1351.                DW   3 DUP(?)  ;Saved BP and return address
  1352.       ARG3     DW   ?
  1353.       ARG2     DW   ?
  1354.       ARG1     DW   ?
  1355.       ARGS     ENDS
  1356.            ...........
  1357.                PUSH BP                 ;save BP register
  1358.                MOV  BP,SP              ;Use BP to address stack
  1359.                MOV   ...,[BP].ARG2     ;retrieve second argument
  1360.                (etc.)
  1361.  
  1362.  
  1363.  
  1364.  
  1365. IBM PC Assembly Language Tutorial                                        22
  1366.  
  1367.  
  1368.  
  1369.     This example uses something called a structure, which is only available
  1370.     in the large assembler; furthermore, it uses it without allocating it,
  1371.     which is not a well-documented option.  However, I find the above
  1372.     approach generally pleasing.  The STRUC is like a DSECT in that it
  1373.     establishes labels as being offset a certain distance from an arbitrary
  1374.     point; these labels are then used in the body of code by beginning them
  1375.     with a period; the construction ".ARG2" means, basically, " +
  1376.     (ARG2-ARGS)."
  1377.  
  1378.     What you are doing here is using BP to address the stack, accounting
  1379.     for the word where you saved the caller's BP and also for the two words
  1380.     which were pushed by the CALL instruction.
  1381.  
  1382. 3.  How big is the stack?  BASIC only gives you an eight word stack to play
  1383.     with.  On the other hand, it doesn't require you to save any registers
  1384.     except the segment registers.  Other languages give you a liberal
  1385.     stack, which makes things a lot easier.  If you have to create a new
  1386.     stack segment for yourself, the easiest thing is to place the stack at
  1387.     the end of your program and:
  1388.  
  1389.          CLI                      ;suppress interrupts while changing the stack
  1390.          MOV  SSAVE,SS            ;save old SS in local storage (old SP
  1391.                                   ; already saved in BP)
  1392.          MOV  SP,CS               ;switch
  1393.          MOV  SS,SP               ;the
  1394.          MOV  SP,OFFSET STACKTOP  ;stack
  1395.          STI                      ;(maybe)
  1396.  
  1397.     Later, you can reverse these steps before returning to the caller.  At
  1398.     the end of your program, you place the stack itself:
  1399.  
  1400.              DW   128 DUP(?)          ;stack of 128 words (liberal)
  1401.     STACKTOP LABEL WORD
  1402.  
  1403.  
  1404. 4.  Make sure you save and restore those registers required by the caller.
  1405.  
  1406. 5.  Be sure to get the right kind of addressibility.  In the FAR call exam-
  1407.     ple, only CS addresses your segment.  If you are careful with your
  1408.     ASSUME statements the assembler will keep track of this fact and gener-
  1409.     ate CS prefixes when you make data references; however, you might want
  1410.     to do something like
  1411.  
  1412.                     MOV AX,CS      ;get current segment address
  1413.                     MOV DS,AX      ;To DS
  1414.                     ASSUME DS:THISSEG
  1415.  
  1416.     Be sure you keep your ASSUMEs in synch with reality.
  1417.  
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423.  
  1424.  
  1425.  
  1426. IBM PC Assembly Language Tutorial                                        23
  1427.  
  1428.  
  1429.  
  1430. Learning about BIOS and the hardware
  1431. ____________________________________
  1432. Learning about BIOS and the hardware
  1433. Learning about BIOS and the hardware
  1434. Learning about BIOS and the hardware
  1435.  
  1436.  
  1437. You can't do everything with DOS calls.  You may need to learn something
  1438. about the BIOS and about the hardware itself.  In this, the Technical Ref-
  1439. erence is a very good thing to look at.
  1440.  
  1441. The first thing you look at in the Technical Reference, unless you are
  1442. really determined to master the whole ball of wax, is the BIOS listings
  1443. presented in Appendix A. Glory be:  here is the whole 8K of ROM which deals
  1444. with low level hardware support layed out with comments and everything.
  1445.  
  1446. In fact, if you are just interested in learning what BIOS can do for you,
  1447. you just need to read the header comments at the beginning of each section
  1448. of the listing.
  1449.  
  1450. BIOS services are invoked by means of the INT instruction; the BIOS occu-
  1451. pies interrupts 10H through 1FH and also interrupt 5H; actually, of these
  1452. seventeen interrupts, five are used for user exit points or data pointers,
  1453. leaving twelve actual services.
  1454.  
  1455. In most cases, a service deals with a particular hardware interface; for
  1456. example, BIOS interrupt 10H deals with the screen.  As with DOS function
  1457. calls, many BIOS services can be passed a function code in the AH register
  1458. and possible other arguments.
  1459.  
  1460. I am not going to summarize the most useful BIOS features here; you will
  1461. see some examples in the next sample program we will look at.
  1462.  
  1463. The other thing you might want to get into with the Tech reference is the
  1464. description of some hardware options, particularly the asynch adapter,
  1465. which are not well supported in the BIOS.  The writeup on the asynch adapt-
  1466. er is pretty complete.
  1467.  
  1468. Actually, the Tech reference itself is pretty complete and very nice as far
  1469. as it goes.  One thing which is missing from the Tech reference is informa-
  1470. tion on the programmable peripheral chips on the system board.  These
  1471. include
  1472.  
  1473.       the 8259 interrupt controller
  1474.       the 8253 timer
  1475.       the 8237 DMA controller and
  1476.       the 8255 peripheral interface
  1477.  
  1478. To make your library absolutely complete, you should order the INTEL data
  1479. sheets for these beasts.
  1480.  
  1481. I should say, though, that the only I ever found I needed to know about was
  1482. the interrupt controller.  If you happen to have the 8086 Family User's
  1483. Manual, the big book put out by INTEL, which is one of the things people
  1484. sometimes buy to learn about 8086 architecture, there is an appendix there
  1485. which gives an adequate description of the 8259.
  1486.  
  1487.  
  1488.  
  1489.  
  1490.  
  1491. IBM PC Assembly Language Tutorial                                        24
  1492.  
  1493.  
  1494.  
  1495. A final example
  1496. _______________
  1497. A final example
  1498. A final example
  1499. A final example
  1500.  
  1501.  
  1502. I leave you with a more substantial example of code which illustrates some
  1503. good elementary techniques; I won't claim its style is perfect, but I think
  1504. it is adequate.  I think this is a much more useful example than what you
  1505. will get with the assembler:
  1506.  
  1507.           PAGE 61,132
  1508.           TITLE SETSCRN -- Establish correct monitor use at boot time
  1509. ;
  1510. ;         This program is a variation on many which toggle the equipment flags
  1511. ;         to support the use of either video option (monochrome or color).
  1512. ;         The thing about this one is it prompts the user in such a way that he
  1513. ;         can select the use of the monitor he is currently looking at (or which
  1514. ;         is currently connected or turned on) without really having to know
  1515. ;         which is which.  SETSCRN is a good program to put first in an
  1516. ;         AUTOEXEC.BAT file.
  1517. ;
  1518. ;         This program is highly dependent on the hardware and BIOS of the IBMPC
  1519. ;         and is hardly portable, except to very exact clones.  For this reason,
  1520. ;         BIOS calls are used in lieu of DOS function calls where both provide
  1521. ;         equal function.
  1522. ;
  1523.  
  1524.  
  1525. OK.  That's the first page of the program.  Notice the PAGE statement,
  1526. which you can use to tell the assembler how to format the listing.  You
  1527. give it lines per page and characters per line.  I have mine setup to print
  1528. on the host lineprinter; I routinely upload my listings at 9600 baud and
  1529. print them on the host; it is faster than using the PC printer.
  1530.  
  1531. There is also a TITLE statement.  This simply provides a nice title for
  1532. each page of your listing.  Now for the second page:
  1533.  
  1534.           SUBTTL -- Provide .COM type environment and Data
  1535.           PAGE
  1536. ;
  1537. ;         First, describe the one BIOS byte we are interested in
  1538. ;
  1539. BIOSDATA  SEGMENT   AT 40H    ;Describe where BIOS keeps his data
  1540.           ORG       10H       ;Skip parts we are not interested in
  1541. EQUIP     DB        ?         ;Equipment flag location
  1542. MONO      EQU       00110000B ;These bits on if monochrome
  1543. COLOR     EQU       11101111B ;Mask to make BIOS think of the color board
  1544. BIOSDATA  ENDS                ;End of interesting part
  1545. ;
  1546. ;         Next, describe some values for interrupts and functions
  1547. ;
  1548. DOS       EQU       21H       ;DOS Function Handler INT code
  1549. PRTMSG    EQU       09H       ;Function code to print a message
  1550. KBD       EQU       16H       ;BIOS keyboard services INT code
  1551. GETKEY    EQU       00H       ;Function code to read a character
  1552. SCREEN    EQU       10H       ;BIOS Screen services INT code
  1553. MONOINIT  EQU       02H       ;Value to initialize monochrome screen
  1554.  
  1555.  
  1556. IBM PC Assembly Language Tutorial                                        25
  1557.  
  1558.  
  1559.  
  1560. ;COLORINIT EQU       03H       ;Value to initialize color screen (80x25)
  1561. COLORINIT EQU      01H       ;Value to initialize color screen (40X25)
  1562. ;
  1563. ;         Now, describe our own segment
  1564. ;
  1565. SETSCRN   SEGMENT             ;Set operating segment for CODE and DATA
  1566. ;
  1567.           ASSUME CS:SETSCRN,DS:SETSCRN,ES:SETSCRN,SS:SETSCRN    ;All segments
  1568. ;
  1569.           ORG       100H      ;Begin assembly at standard .COM offset
  1570. ;
  1571. MAIN      PROC      NEAR      ;COM files use NEAR linkage
  1572.           JMP       BEGIN     ;And, it is helpful to put the data first, but
  1573. ;                             ;then you must branch around it.
  1574. ;
  1575. ;         Data used in SETSCRN
  1576. ;
  1577. CHANGELOC   DD      EQUIP     ;Location of the EQUIP, recorded as far pointer
  1578. MONOPROMPT  DB      'Please press the plus ( + ) key.$'    ;User sees on mono
  1579. COLORPROMPT DB      'Please press the minus ( - ) key.$'   ;User sees on color
  1580.  
  1581.  
  1582. Several things are illustrated on this page.  First, in addition to titles,
  1583. the assembler supports subtitles:  hence the SUBTTL pseudo-op.  Second, the
  1584. PAGE pseudo-op can be used to go to a new page in the listing.  You see an
  1585. example here of the DSECT-style segment in the "SEGMENT AT 40H".  Here, our
  1586. our interest is in correctly describing the location of some data in the
  1587. BIOS work area which really is located at segment 40H.
  1588.  
  1589. You will also see illustrated the EQU instruction, which just gives a sym-
  1590. bolic name to a number.  I don't make a fetish of giving a name to every
  1591. single number in a program.  I do feel strongly, though, that interrupts
  1592. and function codes, where the number is arbitrary and the function being
  1593. performed is the thing of interest, should always be given symbolic names.
  1594.  
  1595. One last new element in this section is the define doubleword (DD) instruc-
  1596. tion.  A doubleword constant can refer, as in this case, to a location in
  1597. another segment.  The assembler will be happy to use information at its
  1598. disposal to properly assemble it.  In this case, the assembler knows that
  1599. EQUIP is offset 10 in the segment BIOSDATA which is at 40H.
  1600.  
  1601.           SUBTTL -- Perform function
  1602.           PAGE
  1603. BEGIN:    CALL      MONOON                  ;Turn on mono display
  1604.           MOV       DX,OFFSET MONOPROMPT          ;GET MONO PROMPT
  1605.           MOV       AH,PRTMSG                     ;ISSUE
  1606.           INT       DOS                           ;IT
  1607.           CALL      COLORON                 ;Turn on color display
  1608.           MOV       DX,OFFSET COLORPROMPT         ;GET COLOR PROMPT
  1609.           MOV       AH,PRTMSG                     ;ISSUE
  1610.           INT       DOS                           ;IT
  1611.           MOV       AH,GETKEY               ;Obtain user response
  1612.           INT       KBD
  1613.           CMP       AL,'+'                  ;Does he want MONO?
  1614.           JNZ       NOMONO
  1615.  
  1616.  
  1617. IBM PC Assembly Language Tutorial                                        26
  1618.  
  1619.  
  1620.  
  1621.           CALL      MONOON                  ;yes.  give it to him
  1622. NOMONO:   RET
  1623. MAIN      ENDP
  1624.  
  1625.  
  1626. The main code section makes use of subroutines to keep the basic flow sim-
  1627. ple.  About all that's new to you in this section is the use of the BIOS
  1628. interrupt KBD to read a character from the keyboard.
  1629.  
  1630. Now for the subroutines, MONOON and COLORON:
  1631.  
  1632.           SUBTTL -- Routines to turn monitors on
  1633.           PAGE
  1634. MONOON    PROC      NEAR                ;Turn mono on
  1635.           LES       DI,CHANGELOC        ;Get location to change
  1636.           ASSUME    ES:BIOSDATA         ;TELL ASSEMBLER ABOUT CHANGE TO ES
  1637.           OR        EQUIP,MONO
  1638.           MOV       AX,MONOINIT         ;Get screen initialization value
  1639.           INT       SCREEN              ;Initialize screen
  1640.           RET
  1641. MONOON    ENDP
  1642. COLORON   PROC      NEAR                ;Turn color on
  1643.           LES       DI,CHANGELOC        ;Get location to change
  1644.           ASSUME    ES:BIOSDATA         ;TELL ASSEMBLER ABOUT CHANGE TO ES
  1645.           AND       EQUIP,COLOR
  1646.           MOV       AX,COLORINIT        ;Get screen initialization value
  1647.           INT       SCREEN              ;Initialize screen
  1648.           RET
  1649. COLORON   ENDP
  1650. SETSCRN   ENDS                          ;End of segment
  1651.           END       MAIN                ;End of assembly; execution at MAIN
  1652.  
  1653.  
  1654. The instructions LES and LDS are useful ones for dealing with doubleword
  1655. addresses.  The offset is loaded into the operand register and the segment
  1656. into ES (for LES) or DS (for LDS).  By telling the assembler, with an
  1657. ASSUME, that ES now addresses the BIOSDATA segment, it is able to correctly
  1658. assemble the OR and AND instructions which refer to the EQUIP byte.  An ES
  1659. segment prefix is added.
  1660.  
  1661. To understand the action here, you simply need to know that flags in that
  1662. particular byte control how the BIOS screen service initializes the adapt-
  1663. ers.  BIOS will only work with one adapter at a time; by setting the equip-
  1664. ment flags to show one or the other as installed and calling BIOS screen
  1665. initialization, we achieve the desired effect.
  1666.  
  1667. The rest is up to you.
  1668.  
  1669.  
  1670.  
  1671.  
  1672.  
  1673.  
  1674.  
  1675.  
  1676.  
  1677.  
  1678. IBM PC Assembly Language Tutorial                                        27
  1679.  
  1680.  
  1681.  
  1682.  
  1683.